package com.wink_172.library.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.widget.RelativeLayout;
import com.wink_172.library.R;


/**
 * 圆角容器
 * https://github.com/wy749814530/RoundLayout/
 * */
public class CircleRelativelayout extends RelativeLayout {

    public  RectF roundRect = new RectF();
    public float roundCorner = 0;
    public  Paint maskPaint = new Paint();
    public  Paint zonePaint = new Paint();

    public CircleRelativelayout(Context context) {
        this(context, null);
    }

    public CircleRelativelayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CircleRelativelayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (attrs != null) {
            TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundLayoutAttr);
            roundCorner = ta.getDimensionPixelSize(R.styleable.RoundLayoutAttr_round_corner, 30);
            ta.recycle();
        }

        maskPaint.setAntiAlias(true);
        maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        maskPaint.setStyle(Paint.Style.FILL);
        //
        zonePaint.setAntiAlias(true);
        zonePaint.setColor(Color.WHITE);

        setBackgroundColor(Color.TRANSPARENT);
    }






    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int w = getWidth();
        int h = getHeight();
        roundRect.set(0, 0, w, h);
    }

    @Override
    public void draw(Canvas canvas) {
        if (roundCorner > 0) {
            canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
            canvas.drawRoundRect(roundRect, roundCorner, roundCorner, zonePaint);
            canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
            super.draw(canvas);
            canvas.restore();

        } else {
            super.draw(canvas);
        }
    }

}
